package com.example.demo1;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Controller
public class TestController {

    @RequestMapping("/test")
    @ResponseBody
    public String test(HttpServletRequest request, HttpSession session, HttpServletResponse response) {
        String sessionId = session.getId();
        //将session的Id存储到名字为JSESSIONID的cookie中
        Cookie cookie = new Cookie("test-cookie", sessionId);
        //设置cookie的有效路径
        cookie.setPath(request.getContextPath());
        cookie.setDomain("localhost");
        response.addCookie(cookie);

        //将session的Id存储到名字为JSESSIONID的cookie中
        Cookie cookie1 = new Cookie("test-cookie", sessionId);
        //设置cookie的有效路径
        cookie1.setPath(request.getContextPath());
        cookie1.setDomain("127.0.0.1");
        response.addCookie(cookie1);

        return "test";
    }

    @RequestMapping("/testCookie")
    @ResponseBody
    public String testCookie(HttpSession session) {
        return "测试cookie";
    }
}
